<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="赛项名称" prop="roleName">
        <el-input v-model="queryParams.roleName" placeholder="请输入赛项名称" clearable style="width: 240px"
                  @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="赛事名称" prop="roleKey">
        <el-input v-model="queryParams.roleKey" placeholder="请输入赛事名称" clearable style="width: 240px"
                  @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 240px">
          <el-option v-for="dict in sys_declare_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="dataList">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="申请编号" prop="id" width="80"/>
      <el-table-column label="赛事名称" prop="eventName" :show-overflow-tooltip="true" align="center"/>
      <el-table-column label="赛项名称" prop="competitionName" :show-overflow-tooltip="true" align="center"/>
      <el-table-column label="主办方" prop="organizers" width="100" align="center"/>
      <el-table-column label="比赛方式" prop="raceType" width="100" align="center"/>
      <el-table-column label="赛道" prop="track" align="center" min-width="120"/>
      <el-table-column label="赛事阶段" prop="stageCurrent" width="100" align="center">
        <template #default="scope">
          <dict-tag :options="sys_race_stageCurrent" :value="scope.row.stageCurrent"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="stageCurrentStatus" width="100" align="center">
        <template #default="scope">
          <dict-tag :options="sys_declare_type" :value="scope.row.stageCurrentStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="审核人阶段" prop="personAudit" width="100" align="center">
        <template #default="scope">
          <dict-tag :options="sys_person_type" :value="scope.row.personAudit"/>
        </template>
      </el-table-column>
      <el-table-column formatter="" label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime,"{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="300">
        <template #default="scope">
          <el-tooltip content="人员信息填报" placement="top">
            <el-button link v-if="scope.row.stageCurrent===2" type="primary" icon="Edit"
                       @click="handleLook(scope.row)"
            >查看人员信息
            </el-button>
          </el-tooltip>
          <el-tooltip content="上报" placement="top">
            <el-button link v-if="scope.row.stageCurrent===2" type="primary" icon="Upload"
                       @click="handleReport(scope.row)"
            >上报
            </el-button>
          </el-tooltip>
          <el-tooltip content="放弃比赛" placement="top">
            <el-button link v-if="scope.row.stageCurrent===2" type="danger" icon="Delete"
                       @click="handleGiveup(scope.row)"
            >放弃比赛
            </el-button>
          </el-tooltip>
          <el-tooltip content="上传竞赛结果" placement="top">
            <el-button link v-if="scope.row.stageCurrent===3" type="primary" icon="Upload"
                       @click="handleUpdateRes(scope.row)">上传竞赛结果
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo"
                v-model:limit="queryParams.pageSize" @pagination="getList"/>

    <!-- 查看人员信息 -->
    <el-dialog :title="title" v-model="open" width="1300px" append-to-body>
      <el-form ref="postRef" :model="tableList" disabled label-width="100px" :inline="true">
        <el-form-item label="赛事名称:" prop="eventName">
          <template #default="scope">
            <dict-tag :options="sys_event_value" :value="tableList.item.eventName"/>
          </template>
        </el-form-item>
        <el-form-item label="赛项名称:" prop="competitionName">
          <el-text>{{ tableList.item.competitionName }}</el-text>
        </el-form-item>
        <el-form-item label="赛道:" prop="track">
          <template #default="scope">
            <dict-tag :options="sys_track_type" :value="tableList.item.track"/>
          </template>
        </el-form-item>
        <el-form-item label="主办方:" prop="organizers">
          <el-text>{{ tableList.item.organizers }}</el-text>
        </el-form-item>
        <el-form-item label="比赛方式:" prop="raceType">
          <template #default="scope">
            <dict-tag :options="sys_race_type" :value="tableList.item.raceType"/>
          </template>
        </el-form-item>
        <el-form-item label="创建时间:" prop="createTime">
          <el-text>{{ tableList.item.createTime }}</el-text>
        </el-form-item>
        <el-divider/>
        <el-table :data="tableList.tableData" style="width: 100%" :rules="rules" border>
          <el-table-column type="index" label="编号" width="70px"/>
          <el-table-column label="选手姓名" width="200px" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.nameStudent`" :rules="rules.nameStudent" align="center">
                <el-input v-model="scope.row.nameStudent" placeholder="选手姓名" style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="联系方式" width="200px" prop="numberPhoneStudent" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.numberPhoneStudent`" :rules="rules.numberPhoneStudent">
                <el-input v-model="scope.row.numberPhoneStudent" placeholder="联系方式"
                          style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="身份证号" width="250px" prop="identityCard" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.identityCard`" :rules="rules.identityCard">
                <el-input v-model="scope.row.identityCard" placeholder="身份证号码" style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="学号" width="200px" prop="numberId" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.numberId`" :rules="rules.numberId">
                <el-input v-model="scope.row.numberId" placeholder="学号" style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="专业" width="200px" prop="major" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.major`" :rules="rules.major">
                <el-input v-model="scope.row.major" placeholder="专业" style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="指导老师姓名" width="200px" prop="nameTeacher" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.nameTeacher`" :rules="rules.nameTeacher">
                <el-input v-model="scope.row.nameTeacher" placeholder="指导老师姓名"
                          style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="指导老师部门" width="200px" prop="deptId" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.deptId`" :rules="rules.deptId" label-width="150px">
                <el-input v-model="scope.row.deptName" placeholder="指导老师部门" style="margin-top: 20px"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="指导老师手机号" width="200px" prop="numberPhoneTeacher" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.numberPhoneTeacher`" :rules="rules.numberPhoneTeacher">
                <el-input v-model="scope.row.numberPhoneTeacher" placeholder="指导老师联系方式"
                          style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-dialog>

    <!--上传竞赛结果-->
    <el-dialog :title="upload.title" v-model="upload.open" width="500px" append-to-body>
      <el-form ref="resRef" :model="form" :rules="rules" label-position="top" label-width="100">
        <el-row>
          <el-col :span="12">
            <el-form-item label="参赛时间" prop="joinTime">
              <div class="block">
                <el-date-picker
                    type="date"
                    v-model="form.joinTime"
                    placeholder="请选择一天"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    size="default"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="获奖等级" prop="awardGrade">
              <el-input v-model="form.awardGrade" placeholder="请输入获奖等级" style="width: 200px"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否获奖" prop="hasAward">
              <el-select v-model="form.hasAward">
                <el-option label="是" :value="true"/>
                <el-option label="否" :value="false"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别" prop="type">
              <el-select v-model="form.type" placeholder="请选择比赛方式">
                <el-option v-for="dict in sys_race_type" :value="dict.value" :key="dict.value" :label="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type=“flex” style="align-items: center">
          <el-col>
            <el-form-item label="指导老师部门" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入第一指导教师所属单位" style="width: 80%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Mydeclare">
import {getToken} from '@/utils/_auth'
import {
  abandon,
  declareList,
  getContestTeam,
  giveUp,
  staffReport,
  uploadContestResv2
} from '@/api/contestment/mydeclare'

const {proxy} = getCurrentInstance();
const {
  sys_declare_type,
  sys_race_stageCurrent,
  sys_person_type,
  sys_race_type
} = proxy.useDict("sys_declare_type", "sys_race_stageCurrent", "sys_person_type", "sys_race_type");
const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  type: 3,
  module: "xx",
  // 设置上传的请求头部
  headers: {AuthToken: getToken()},
  // 上传的地址
  url: `/api/admin/common/upload`
});
const data = reactive({
  form: {},
  queryParams: {
    pageNo: 0,
    pageSize: 10,
    name: undefined,
    status: undefined
  },
  rules: {
    joinTime: [{required: true, message: "参赛时间不能为空", trigger: "blur"}],
    awardGrade: [{required: true, message: "获奖等级为 1 到 10 个字符", trigger: "blur"}],
    hasAward: [{required: true, message: "是否获奖不能为空", trigger: "blur"}],
    type: [{required: true, message: "参赛方式不能为空", trigger: "blur"}],
    deptName: [{required: true, message: "指导老师部门为 1 到 10 个字符", trigger: "blur"}]
  },
});

const tableList = ref({
  item: {
    eventName: '',
    competitionName: '',
    track: '',
    raceType: '',
    createTime: ''
  },
  tableData: [
    {
      deptId: '',
      identityCard: '',
      major: '',
      nameStudent: '',
      nameTeacher: '',
      numberId: '',
      numberPhoneStudent: '',
      numBerPhoneTeacher: '',
    }
  ]
})
const {queryParams, form, rules} = toRefs(data);


/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 获取我的申报列表数据 */
function getList() {
  loading.value = true;
  declareList(proxy.addDateRange(queryParams.value)).then((res) => {
    loading.value = false;
    total.value = res.data.total;
    dataList.value = res.data.result;
    console.log(dataList.value)
  });
}

/** 重置新增表以及其他数据*/
function reset() {
  form.value = {
    id: undefined,
    competitionName: undefined,    // 赛项名称
    eventsName: undefined,  // 赛事名称
    name: undefined,  // 姓名
    idCard: undefined,  // 身份证
    age: undefined,  // 年龄
    stageCurrentStatus: '1', // 0待申报 1申报成功 2申报中 3驳回
  };
}

//查看人员信息
function handleLook(row) {
  getContestTeam(row.id).then(response => {
    tableList.value.item = response.data.result.contest
    tableList.value.tableData = response.data.result.persons
    title.value = "信息查看"
    open.value = true
    // }
  })
}

const handleRemove = (file) => {
  console.log(file)
}

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleDownload = (file) => {
  console.log(file)
}

/** 上传竞赛结果 */
function handleUpdateRes(row) {
  form.value.id = row.id
  upload.title = "上传竞赛结果"
  upload.open = true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  form.value.url = response.data.url;
  form.value.type = 3;
  form.value.name = response.data.name;
  form.value.extensionName = response.data.extensionName;
  form.value.size = response.data.size;
  form.value.fileSize = response.data.fileSize;
  form.value.isSuccess = response.data.isSuccess;
};

/** 提交竞赛结果 */
function submitFileForm() {
  console.log(form.value);
  uploadContestResv2(form.value.id, form.value).then(response => {
    if (response.data) {
      proxy.$modal.msgSuccess("提交成功")
      upload.open = false
      getList()
    }
  })
};

/** 上报 */
function handleReport(row) {
  const contestIds = row.id || ids.value;
  // 上报竞赛
  form.value.optionType = 2;  // 提交
  switch (row.stageCurrent) {
    case 2:
      proxy.$modal.confirm(`确定提交${contestIds}的数据`).then(function () {
        return staffReport(contestIds);
      }).then(res => {
        getList();
        proxy.$modal.msgSuccess("提交成功")
      }).catch(() => {
      });
      return;
  }
}

/** 放弃比赛 */
function handleGiveup(row) {
  console.log(row)
  const res = {
    competitionName : row.competitionName,
    eventName :row.eventName,
    id :row.id
  }
  switch (row.stageCurrent) {
    case 2:
      proxy.$modal.confirm(`确定放弃id为 ${row.id} 的比赛`).then(function () {
        abandon(res).then(response => {
          proxy.$modal.msgSuccess(`${response.msg}`);
          getList();
        }).catch(() => {
        })
      })
      return

  }
}

getList()
</script>
